<template>
  <div class="main">
    <!-- 搜索区域 -->
    <div class="search">
      <el-form :model="res" ref="searchForm" :inline="true" class="search-form">
        <el-form-item label="资源名称：" prop="name">
          <el-input v-model="res.name" style="width: 150px" placeholder="请输入资源名称" clearable />
        </el-form-item>

        <el-form-item label="资源类型：" prop="type">
          <el-select v-model="res.type" style="width: 120px" placeholder="请选择类型" clearable>
            <el-option label="路由" value="1" />
            <el-option label="菜单" value="2" />
            <el-option label="按钮" value="3" />
            <el-option label="数据" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="请求方式：" prop="method">
          <el-select v-model="res.method" style="width: 120px" placeholder="请选择请求方式" clearable>
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>

        <el-form-item label="请求地址：" prop="value">
          <el-input v-model="res.value" style="width: 180px" placeholder="请输入请求地址" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search" :icon="Search">查询</el-button>
          <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
          <el-button type="success" @click="add" :icon="Plus">添加</el-button>
          <el-button type="danger" @click="deleteRows" :icon="Delete">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据展示区域 -->
    <div class="data">
      <div class="gird">
        <el-table :data="tableData" border style="width: 100%"
                  :header-cell-style="{ textAlign: 'center', background: '#f5f7fa', fontWeight: 'bold' }"
                  :cell-style="{ textAlign: 'center' }" ref="tableRef"
                  v-loading="loading"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" fixed="left" />
          <el-table-column prop="name" label="资源名称" width="150" fixed="left" />
          <el-table-column prop="type" label="资源类型" width="100">
            <template #default="scope">
              {{ getTypeText(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="method" label="请求方式" width="100" />
          <el-table-column prop="value" label="请求地址" width="200" show-overflow-tooltip />
          <el-table-column prop="description" label="备注" width="200" show-overflow-tooltip />

          <el-table-column prop="createdBy" label="创建人" width="120" />
          <el-table-column prop="createdTime" label="创建时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updatedBy" label="最后修改人" width="120" />
          <el-table-column prop="updatedTime" label="更新时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.updatedTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button size="small" :icon="Edit" @click="editRow(scope.row)" type="primary">编辑</el-button>
              <el-button size="small" :icon="Delete" @click="deleteRow(scope.row)" type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="pi.pageNo" v-model:page-size="pi.pageSize"
                       :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                       :total="pi.total" background @size-change="paginate" @current-change="paginate" />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="show" :title="title" width="600" draggable :close-on-click-modal="false">
      <el-form :model="rfm" ref="formRef" label-width="100px" :rules="rules">
        <el-form-item label="资源名称：" prop="name">
          <el-input v-model="rfm.name" placeholder="请输入资源名称" />
        </el-form-item>

        <el-form-item label="资源类型：" prop="type">
          <el-select v-model="rfm.type" placeholder="请选择资源类型">
            <el-option label="路由" value="1" />
            <el-option label="菜单" value="2" />
            <el-option label="按钮" value="3" />
            <el-option label="数据" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="请求方式：" prop="method">
          <el-select v-model="rfm.method" placeholder="请选择请求方式">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>

        <el-form-item label="请求地址：" prop="value">
          <el-input v-model="rfm.value" placeholder="请输入请求地址" />
        </el-form-item>

        <el-form-item label="备注：" prop="description">
          <el-input v-model="rfm.description" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="show = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { findAll, deleteById, save, update, deleteAll } from '@/api/ResourceApi'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Search, Refresh, Delete } from '@element-plus/icons-vue'

// 表格引用
const tableRef = ref()
const formRef = ref()
// 表格数据
const tableData = ref([])
// 对话框显示状态
const show = ref(false)
// 加载状态
const loading = ref(false)
// 对话框标题
const title = ref("新增资源")
// 选中行
const selectedRows = ref([])

// 搜索条件
const res = reactive({
  name: "",
  type: "",
  method: "",
  value: ""
})

// 表单数据
const rfm = reactive({
  name: "",
  type: "",
  method: "",
  value: "",
  description: ""
})

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入资源名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
  method: [{ required: true, message: '请选择请求方式', trigger: 'change' }],
  value: [{ required: true, message: '请输入请求地址', trigger: 'blur' }]
})

// 分页信息
const pi = ref({
  pageNo: 1,
  pageSize: 15,
  total: 0,
})

// 资源类型映射
const typeMap = {
  '1': '路由',
  '2': '菜单',
  '3': '按钮',
  '4': '数据'
}

// 组件挂载时加载数据
onMounted(() => {
  search()
})

// 获取资源类型文本
function getTypeText(type) {
  return typeMap[type] || type
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString()
}

// 处理选中行变化
function handleSelectionChange(selection) {
  selectedRows.value = selection
}

// 搜索方法
async function search() {
  try {
    loading.value = true

    // 构建查询参数对象
    const searchParams = {
      pageNo: pi.value.pageNo,
      pageSize: pi.value.pageSize
    }

    // 手动添加所有查询条件
    if (res.name) searchParams.name = res.name
    if (res.type) searchParams.type = res.type
    if (res.method) searchParams.method = res.method
    if (res.value) searchParams.value = res.value

    console.log("发送的查询参数:", searchParams)

    let resp = await findAll(pi.value.pageNo, pi.value.pageSize, searchParams)

    console.log("API响应:", resp)

    if (resp && resp.code === "200" && resp.data) {
      tableData.value = resp.data.records || []
      pi.value.total = resp.data.total || 0
      pi.value.pageNo = resp.data.current || 1
      pi.value.pageSize = resp.data.size || 20

      ElMessage.success(`加载成功，共 ${resp.data.total} 条数据`)
    } else {
      ElMessage.error("数据格式错误")
    }
  } catch (error) {
    console.error("搜索失败:", error)
    ElMessage.error("获取数据失败")
  } finally {
    loading.value = false
  }
}

// 分页查询
function paginate() {
  search()
}

// 重置搜索
function resetSearch() {
  Object.keys(res).forEach(key => {
    res[key] = ""
  })
  pi.value.pageNo = 1
  search()
}

// 删除单行
function deleteRow(row) {
  ElMessageBox.confirm(`确定要删除资源【${row.name}】吗？`, "警告", {
    type: "warning",
  }).then(async () => {
    let resp = await deleteById(row.id)
    if (resp.code === "200") {
      ElMessage.success("删除成功")
      search()
    } else {
      ElMessage.error(resp.msg || "删除失败")
    }
  }).catch(() => {})
}

// 批量删除
function deleteRows() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的资源")
    return
  }

  const names = selectedRows.value.map(row => row.name).join('、')
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个资源吗？\n${names}`, "警告", {
    type: "warning",
  }).then(async () => {
    const ids = selectedRows.value.map(row => row.id)
    let resp = await deleteAll(ids)
    if (resp.code === "200") {
      ElMessage.success("批量删除成功")
      search()
    } else {
      ElMessage.error(resp.msg || "删除失败")
    }
  }).catch(() => {})
}

// 添加资源
function add() {
  show.value = true
  title.value = "新增资源"
  // 重置表单数据
  Object.keys(rfm).forEach(key => {
    rfm[key] = ""
  })
}

// 提交表单
function submitForm() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = { ...rfm }
        let resp
        if (formData.id) {
          resp = await update(formData)
        } else {
          resp = await save(formData)
        }

        if (resp.code === "200") {
          ElMessage.success(formData.id ? "修改成功" : "添加成功")
          show.value = false
          search()
        } else {
          ElMessage.error(resp.msg || "操作失败")
        }
      } catch (error) {
        console.error("操作失败:", error)
        ElMessage.error("操作失败")
      }
    }
  })
}

// 编辑行
function editRow(row) {
  show.value = true
  title.value = "修改资源"
  // 复制行数据到表单
  Object.assign(rfm, row)
}
</script>

<style scoped>
.main {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.data {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.gird {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table :deep(.el-table__cell) {
  padding: 8px 0;
}

.el-table :deep(.cell) {
  line-height: 1.5;
}

.dialog-footer {
  text-align: right;
}
</style>